//
//  MeViewController.m
//  PigMarket
//
//  Created by Felix on 2019/3/4.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "MeViewController.h"
#import "SystemSetingViewController.h"
#import "SelectTagsViewController.h"
#import "LoginViewController.h"
#import "MessageViewController.h"
#import "AddressViewController.h"
#import "CommonQuestionsViewController.h"
#import "PrefectPersonalInfoViewController.h"
#import "ModifyPhotoViewController.h"
#import "DiscountCouponViewController.h"
#import "MyAdoptedViewController.h"
#import "MyAssetViewController.h"
#import "InviteFriendsViewController.h"


#import "MeHeaderView.h"
#import "OrderStatusView.h"
#import "PhotoAlbumView.h"
#import "MyServiceView.h"


#import "UIView+Add.h"

#import "MeatMeHeader.h"


@interface MeViewController ()

/**
 meScrollView
 */
@property (nonatomic , strong) UIScrollView *meScrollView;
/**
 contentView
 */
@property (nonatomic , strong) UIView *contentView;
/**
 headerViewbg
 */
@property (nonatomic , strong) UIImageView *headerViewbg;
/**
 unLoginTopView
 */
@property (nonatomic , strong) UIView *unLoginTopView;
/**
 unLoginIcon
 */
@property (nonatomic , strong) UIImageView *unLoginIcon;
/**
 unLoginTitle
 */
@property (nonatomic , strong) UILabel *unLoginTitle;
/**
 bgView
 */
@property (nonatomic , strong) UIView *bgView;
/**
 meHeaderView
 */
@property (nonatomic , strong) MeHeaderView *meHeaderView;
/**
 orderStatusView
 */
@property (nonatomic , strong) OrderStatusView *orderStatusView;
/**
 photoAlbumView
 */
@property (nonatomic , strong) PhotoAlbumView *photoAlbumView;
/**
 inviteFriendImg
 */
@property (nonatomic , strong) UIImageView *inviteFriendImg;
/**
 myServiceView
 */
@property (nonatomic , strong) MyServiceView *myServiceView;
/**
 requestData
 */
@property (nonatomic , strong) NSMutableArray *requestDataArr;
/**
 UserDetailInfo
 */
@property (nonatomic , strong) UserDetailInfo *userDetailInfo;
/**
 isLogin
 */
@property (nonatomic , assign) BOOL isLogin;


@property (nonatomic, strong) MeatMeHeader *header;

@end

@implementation MeViewController

#pragma mark - view life cycle

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    UserInfo *userInfo = [UserInfoDataProvider sharedInstance].userInfo;
    self.isLogin = userInfo.isLogin;
    self.isLogin = YES;
     if (self.isLogin) {//登录状态
        self.meHeaderView.hidden = NO;
        self.unLoginTopView.hidden = YES;
         [self requestHeaderData];
     }else {
         self.meHeaderView.hidden = YES;
         self.unLoginTopView.hidden = NO;
     }
}

- (void)setupUI
{
        [self setupNav];
        [self setUpView];
}



#pragma mark - init method

- (void)setupNav {
    // 导航栏透明
   // [[NavigationBarManager sharedInstance] setupNavigationBarClear:self.navigationController];
    //申请服务商
    UIButton *servicerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    servicerBtn.frame = CGRectMake(0, 0, 116 * [JTool getScreenWidthScale], 21);
    servicerBtn.layer.cornerRadius = 11;
    servicerBtn.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
    [servicerBtn setTitle:@"申请成为服务商" forState:UIControlStateNormal];
    servicerBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [servicerBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [servicerBtn addTarget:self action:@selector(servicerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:servicerBtn];
    
    //设置
    UIBarButtonItem *setupBtn = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"user_setup"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(settupTapped)];
    //消息
    UIBarButtonItem *messageBtn = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"user_message"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(messageBtnTapped)];
    
    self.navigationItem.rightBarButtonItems = @[messageBtn,setupBtn];
}


- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}


- (void)initView {
    [self.view addSubview:self.headerViewbg];
    [self.view addSubview:self.meScrollView];
    [self.meScrollView addSubview:self.contentView];
    
    [self.contentView addSubview:self.unLoginTopView];
    [self.unLoginTopView addSubview:self.unLoginIcon];
    [self.unLoginTopView addSubview:self.unLoginTitle];
    
    [self.contentView addSubview:self.meHeaderView];
    [self.contentView addSubview:self.bgView];
    [self.bgView addSubview:self.orderStatusView];
    [self.bgView addSubview:self.inviteFriendImg];
    [self.bgView addSubview:self.photoAlbumView];
    [self.bgView addSubview:self.myServiceView];
}


- (void) initLayout {
    [self.headerViewbg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(-TopBarHeight);
        make.height.mas_equalTo(ScaleHeight(184));
    }];
    [self.meScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.mas_equalTo(0);
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(-TopBarHeight);
    }];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_WIDTH);
    }];
    [self.unLoginTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(self.headerViewbg.mas_height);
    }];
    [self.unLoginIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(22);
        make.bottom.mas_equalTo(-18);
    }];
    [self.unLoginTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.unLoginIcon.mas_right).offset(20);
        make.centerY.mas_equalTo(self.unLoginIcon.mas_centerY);
    }];
    [self.meHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
//        make.top.mas_equalTo(-TopBarHeight);
        make.height.mas_equalTo(self.headerViewbg.mas_height);
    }];
    
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(self.meHeaderView.mas_bottom);
    }];
    [self.orderStatusView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.top.mas_equalTo(12);
    }];
    [self.inviteFriendImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(80 * [JTool getScreenWidthScale]);
        make.top.mas_equalTo(self.orderStatusView.mas_bottom).offset(10);

    }];
    [self.photoAlbumView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.right.mas_equalTo(-12);
        make.height.mas_equalTo(126);
        make.top.mas_equalTo(self.inviteFriendImg.mas_bottom).offset(10);
    }];
    [self.myServiceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.top.mas_equalTo(self.photoAlbumView.mas_bottom).offset(10);
        make.bottom.mas_equalTo(0);
    }];
}



- (void) initAction {
    // 未登录头部点击
    UITapGestureRecognizer *unLoginHeaderTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(unLoginHeaderTapped)];
    [self.unLoginTopView addGestureRecognizer:unLoginHeaderTap];
    // 头部点击
    UITapGestureRecognizer *headerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerTapped)];
    [self.meHeaderView addGestureRecognizer:headerTap];
    
    //邀请好友
    UITapGestureRecognizer *inviteFriendTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(inviteFriendTapped)];
    [self.inviteFriendImg addGestureRecognizer:inviteFriendTap];
    
    // 查看全部订单
    UITapGestureRecognizer *allOrdersTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(allOrdersTapped)];
    [self.orderStatusView addGestureRecognizer:allOrdersTap];
    // 订单状态点击事件
    for (int i = 0; i < self.orderStatusView.statusBtnArray.count; i++) {
        HButtonView *btn = self.orderStatusView.statusBtnArray[i];
        btn.tapped = ^{
            UIViewController *vc = nil;
            switch (i) {
                case 0: { // 待付款
                    PMLog(@"待付款");
                }
                    break;
                case 1: { // 待发货
                    PMLog(@"待发货");
                }
                    break;
                case 2: { // 待收货
                    PMLog(@"待收货");
                }
                    break;
                case 3: { // 待评价
                    PMLog(@"待评价");
                }
                    break;
                case 4: { // 退款/售后
                    PMLog(@"退款/售后");
                }
                    break;
            }
        };
    }
    // 查看全部照片
    UITapGestureRecognizer *allPhotosTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(allPhotosTapped)];
    [self.photoAlbumView addGestureRecognizer:allPhotosTap];
    
    //我的服务点击
    @weakify(self);
    [self.myServiceView setMyServiceBlock:^(NSInteger index) {
        @strongify(self);
        UIViewController *vc = nil;
        switch (index) {
            case 0://店铺收藏
                vc = [[DiscountCouponViewController alloc] init];

                break;
            case 1://豚券
            {
                vc = [[DiscountCouponViewController alloc] init];
            }
                break;
            case 2://我的资产
            {
                vc = [[MyAssetViewController alloc] init];

            }
                break;
            case 3://我的领养
            {
                vc = [[MyAdoptedViewController alloc] init];
                
            }

                break;
            case 4://购物车
            {
                vc = [[DiscountCouponViewController alloc] init];

            }
                break;
            case 5://收货地址
            {
                vc = [[AddressViewController alloc] init];
            }
                break;
            case 6://常见问题
            {
                vc = [[CommonQuestionsViewController alloc] init];
            }
                break;
            case 7://帮助
            {
                vc = [[DiscountCouponViewController alloc] init];

            }
                break;
            case 8://我的店铺
            {
                vc = [[DiscountCouponViewController alloc] init];

            }
                break;
            default:
                
                break;
        }
        [self checkLoginStatusToPushVC:vc];
    }];
}


- (void)initData {

}

#pragma mark - delegate

#pragma mark - target action
- (void)servicerBtnClick {
    if (![self userIsLogin]) {
        return;
    }
    
}
- (void)settupTapped {

    [self checkLoginStatusToPushVC:[[SystemSetingViewController alloc] init]];
}
- (void)messageBtnTapped {
    [self checkLoginStatusToPushVC:[[MessageViewController alloc] init]];

                                                                                                                                                                                                                                                           }

- (void)unLoginHeaderTapped {
    LoginViewController *loginViewController = [[LoginViewController alloc] init];
    [self.navigationController pushViewController:loginViewController animated:YES];
}
- (void)headerTapped {
    
    PrefectPersonalInfoViewController *modifyUserInfoVC = [[PrefectPersonalInfoViewController alloc] init];
    modifyUserInfoVC.title = ModifyPersonalInfoTitle;
    modifyUserInfoVC.userInfoModel = self.userDetailInfo;
    [self.navigationController pushViewController:modifyUserInfoVC animated:YES];
}
- (void)allOrdersTapped {
//    [self checkLoginStatusToPushVC:nil];
    PMLog(@"查看全部订单点击事件");
}
- (void)inviteFriendTapped {
    [self checkLoginStatusToPushVC:[[InviteFriendsViewController alloc] init]];
}
- (void)allPhotosTapped {
 
    ModifyPhotoViewController *modifyPhotoViewController = [[ModifyPhotoViewController alloc] init];
    modifyPhotoViewController.title = CommonPhotoTitle;
    [self checkLoginStatusToPushVC:[[InviteFriendsViewController alloc] init]];
}

#pragma mark - private method
//跳转判断是否登录   否则跳登录页
- (void)checkLoginStatusToPushVC:(UIViewController *)vc {
    [self pushToViewController:^{
        [self.navigationController pushViewController:vc animated:YES];
    }];
}

- (void)loginStatusChanged:(NSNotification *)notification {
    if ([UserInfoDataProvider sharedInstance].userInfo.isLogin) { // 登录成功
        self.meHeaderView.hidden = NO;
        self.unLoginTopView.hidden = YES;
    }
}


//个人资料数据请求
- (void)requestHeaderData {
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    @weakify(self);
    [[[PigMarketApi sharedInstance] getUserDetailInfoWithMemberId:memberId] subscribeNext:^(UserDetailInfo * _Nullable userDetailInfo) {
        @strongify(self);
        self.meHeaderView.userDetailModel = userDetailInfo;
        self.userDetailInfo = userDetailInfo;
        
        //保存是否三方绑定标识
        
        UserInfo *userInfo = [UserInfoDataProvider sharedInstance].userInfo;
        userInfo.qqOpenid = userDetailInfo.qqOpenid;
        userInfo.wbOpenid = userDetailInfo.wbOpenid;
        userInfo.wxOpenid = userDetailInfo.wxOpenid;
        userInfo.withdrawWx = userDetailInfo.withdrawWx;
        userInfo.memberName = userDetailInfo.memberName;//实名认证
        [UserInfoDataProvider sharedInstance].userInfo = userInfo;
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


- (BOOL)userIsLogin {
    if (!self.isLogin) {
        [self toastWithContent:@"请先登录/注册"];
        return NO;
    }
    return YES;
}

#pragma mark - tableview delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    return 100;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *sectionView = [[UIView alloc] init];
    sectionView.backgroundColor = mBackgroudColor;
    return sectionView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BaseIndentationTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BaseIndentationTableCell"];
    
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}



#pragma mark - getter and setter

- (UIScrollView *)meScrollView {
    if (!_meScrollView) {
        _meScrollView = [[UIScrollView alloc] init];
    }
    return _meScrollView;
}


- (UIImageView *)headerViewbg {
    if (!_headerViewbg) {
        _headerViewbg = [[UIImageView alloc] init];
        _headerViewbg.image = [UIImage imageNamed:@"user_headerviewbg"];
    }
    return _headerViewbg;
}


- (UIView *)contentView {
    if (!_contentView) {
        _contentView = [[UIView alloc] init];
    }
    return _contentView;
}


- (UIView *)unLoginTopView {
    if (!_unLoginTopView) {
        _unLoginTopView = [[UIView alloc] init];
    }
    return _unLoginTopView;
}


- (UIImageView *)unLoginIcon {
    if (!_unLoginIcon) {
        _unLoginIcon = [[UIImageView alloc] init];
        _unLoginIcon.image = [UIImage imageNamed:@"user_header_default"];
    }
    return _unLoginIcon;
}


- (UILabel *)unLoginTitle {
    if (!_unLoginTitle) {
        _unLoginTitle = [[UILabel alloc] init];
        _unLoginTitle.textColor = [UIColor colorWithHexString:@"#ffffff"];
        _unLoginTitle.font = [UIFont xLargerFont];
        _unLoginTitle.text = @"登录/注册";
    }
    return _unLoginTitle;
}


- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] init];
        _bgView.backgroundColor = [UIColor colorWithHexString:@"#f7f7f7"];
    }
    return _bgView;
}


- (MeHeaderView *)meHeaderView {
    if (!_meHeaderView) {
        _meHeaderView = [[MeHeaderView alloc] init];
        _meHeaderView.hidden = YES;
    }
    return _meHeaderView;
}
- (OrderStatusView *)orderStatusView {
    if (!_orderStatusView) {
        _orderStatusView = [[OrderStatusView alloc] init];
        _orderStatusView.backgroundColor = [UIColor colorWithHexString:@"#ffffff"];
        _orderStatusView.layer.cornerRadius = 6;
        _orderStatusView.layer.masksToBounds = YES;
    }
    return _orderStatusView;
}


- (UIImageView *)inviteFriendImg {
    if (!_inviteFriendImg) {
        _inviteFriendImg = [[UIImageView alloc] init];
        _inviteFriendImg.userInteractionEnabled = YES;
        _inviteFriendImg.image = [UIImage imageNamed:@"user_invitefriend"];
    }
    return _inviteFriendImg;
}


- (PhotoAlbumView *)photoAlbumView {
    if (!_photoAlbumView) {
        _photoAlbumView = [[PhotoAlbumView alloc] init];
        _photoAlbumView.backgroundColor = [UIColor colorWithHexString:@"#ffffff"];
        _photoAlbumView.layer.cornerRadius = 6;
        _photoAlbumView.layer.masksToBounds = YES;
    }
    return _photoAlbumView;
}


- (MyServiceView *)myServiceView {
    if (!_myServiceView) {
        _myServiceView = [[MyServiceView alloc] init];
        _myServiceView.backgroundColor = [UIColor colorWithHexString:@"#ffffff"];
        _myServiceView.layer.cornerRadius = 6;
        _myServiceView.layer.masksToBounds = YES;
    }
    return _myServiceView;
}


- (NSMutableArray *)requestDataArr {
    if (!_requestDataArr) {
        _requestDataArr = [[NSMutableArray alloc] init];
    }
    return _requestDataArr;
}

#pragma mark - notifications

- (void)addNotifications
{
    [kNotificationCenter addObserver:self selector:@selector(loginStatusChanged:) name:NotificationLoginStatusChanged object:nil];
}

- (void)removeNotifications
{
    [kNotificationCenter removeObserver:self name:NotificationLoginStatusChanged object:nil];
}



@end
